package cn.itcast.bos.service.system.impl;

import cn.itcast.bos.dao.system.RoleRepository;
import cn.itcast.bos.dao.system.UserRepository;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: SOS
 * @create: 2018-03-09 16:41
 */

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public void save(User model, String[] roleIds) {
        userRepository.save(model);
        if (roleIds != null) {
            for (int i = 0; i < roleIds.length; i++) {
                String roleId = roleIds[i];
                Role role = roleRepository.findOne(Integer.parseInt(roleId));
                model.getRoles().add(role);
            }
        }
    }
}
